package com.ruoyi.im.websocket.protocol;


import com.ruoyi.im.domain.CcsChatMessage;

import java.util.Date;

/**
 * websocket 消息编解码器
 *  protocol: sessionId:from:to:type:message
 *
 * @author zzh
 */
public class WebSocketCodec {

    /**
     * 编码 ==> sessionId:from:to:type:message
     * @param msg 消息实体
     * @return str
     */
    public static String encode(CcsChatMessage msg) {
        StringBuffer sb = new StringBuffer();
        sb
                .append(msg.getLinkId())
                .append(":")
                .append(msg.getSendId())
                .append(":")
                .append(msg.getReceiveId())
                .append(":")
                .append(msg.getMessageType())
                .append(":")
                .append(msg.getContent());
        return sb.toString();
    }

    /**
     * 解码
     * @param packet 字符串
     * @return CcsChatMessage
     */
    public static CcsChatMessage decode(String packet) {
        // 1. 解析
        String[] params = packet.split(":");
        if (params.length != 5) return null;
        // 2. 构造 消息实体
        CcsChatMessage ccsChatMessage = new CcsChatMessage();
        ccsChatMessage.setLinkId(Long.parseLong(params[0]));
        ccsChatMessage.setSendId(Long.parseLong(params[1]));
        ccsChatMessage.setReceiveId(Long.parseLong(params[2]));
        ccsChatMessage.setMessageType(params[3]);
        ccsChatMessage.setContent(params[4]);
        ccsChatMessage.setCreateTime(new Date());
        return ccsChatMessage;
    }

}
